<template>
  <Form class="xtx-form" v-slot="{errors}" :validate-schema="mySchema" autocomplete="off" ref="formCom">
    <div class="user-info">
      <img :src="avatar" alt="">
      <p>Hi，{{ nickName }} 欢迎您，完成绑定后可以QQ账号一键登录哦</p>
    </div>
    <div class="xtx-form-item">
     <div class="field">
      <i class="icon iconfont icon-phone"></i>
      <Field :class="{err:errors.mobile}" name="mobile" v-model="form.mobile" type="text" class="input" placeholder="绑定手机号码" />
     </div>
      <div class="error" v-if="errors.mobile">{{ errors.mobile }}</div>
    </div>
    <div class="xtx-form-item">
    <div class="field">
        <i class="icon iconfont icon-code"></i>
        <Field :class="{err:errors.code}" name="code" v-model="form.code" type="text" class="input" placeholder="短信验证码" />
        <span class="code" @click="send()">{{ time > 0? `${time}秒后重新发送` : '发送验证码' }}</span>
      </div>
      <div class="error" v-if="errors.code">{{ errors.code }}</div>
    </div>
    <a href="javascript:;" class="submit" @click="submit()">立即绑定</a>
  </Form>
</template>

<script>
import QC from 'qc'
import Message from '@/components/library/Message'
import { ref, reactive } from 'vue'
import { Form, Field } from 'vee-validate'
import schema from '@/utils/vee-validate-schema'
import { useIntervalFn } from '@vueuse/core'
import { userQQloginCode, userQQloginBind } from '@/api/user'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
export default {
  name: 'CallbackBind',
  props: {
    unionId: {
      type: String,
      default: ''
    }
  },
  components: {
    Form,
    Field
  },
  setup (props, { emit }) {
    // 准备信息 unionId(openId) qq头像 昵称
    // 完成表单校验
    // 发送验证码（校验定义api 调用，完成倒计时）
    // 进行绑定（绑定成功就是登录成功）
    const nickName = ref(null)
    const avatar = ref(null)
    if (QC.Login.check()) {
      QC.api('get_user_info').success(res => {
        avatar.value = res.data.figureurl_qq_1
        nickName.value = res.data.nickname
        console.log(res)
      })
    }

    // 表单数据对象
    const form = reactive({
      mobile: null,
      code: null
    })

    // 校验数据规则
    const mySchema = {
      mobile: schema.mobile,
      code: schema.code
    }

    // 发送验证码
    // pause 暂停 resume 开始
    // useIntervalFn(回调函数，执行间隔，是否立即执行)
    // 倒计时存储
    const time = ref(null)
    const formCom = ref(null)
    const { pause, resume } = useIntervalFn(() => {
      time.value--
      if (time.value === 0) {
        pause()
      }
      resume()
    }, 1000, false)

    // 点击发送验证码
    const send = () => {
      // 将输入框的号码传到校验函数进行校验 返回Boolean
      const valid = mySchema.mobile(form.mobile)
      if (valid === true) {
        // 校验成功
        userQQloginCode(form.mobile).then(data => {
          console.log(data)
        })
        time.value = 60
        Message({ type: 'success', text: '发送成功' })
        resume()
      } else {
        // 校验失败
        formCom.value.setFieldError('mobile', valid)
      }
    }

    const store = useStore()
    const router = useRouter()
    // 点击立即绑定的时候 触发表单校验
    const submit = async () => {
      console.log(props.unionId)
      const valid = formCom.value.validate()
      if (valid) {
        userQQloginBind({
          unionId: props.unionId,
          ...form
        }).then(data => {
          console.log(data)
          const { id, mobile, token, nickname, avatar, account } = data.result
          store.commit('user/setUser', { id, mobile, token, nickname, avatar, account })

          // 绑定成功后合并购物车商品
          store.dispatch('cart/mergeLocalCart').then(() => {
            router.push(store.state.user.redirectUrl || '/')
            Message({ text: '绑定成功', type: 'success' })
          })
        }).catch(e => {
          Message({ text: '绑定失败', type: 'error' })
        })
      }
    }
    return { form, mySchema, formCom, time, send, submit, avatar, nickName }
  }
}
</script>

<style lang="less" scoped>
.xtx-form {
  .user-info {
    width: 320px;
    height: 70px;
    margin: 0 auto;
    display: flex;
    background: #f2f2f2;
    align-items: center;
    padding: 0 10px;
    margin-bottom: 25px;
    img {
      background: #f2f2f2;
      width: 50px;
      height: 50px;
    }
    p {
      padding-left: 10px;
    }
  }
  .code {
    position: absolute;
    right: 0;
    top: 0;
    line-height: 50px;
    min-width: 80px;
    padding: 0 4px;
    color: #999;
    &:hover {
      cursor: pointer;
    }
  }
}
</style>
